Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Course Overview
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Root to Leaf Path Pattern (medium)
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Smallest String Starting From Leaf

Problem Statement

You are given a binary tree where each node contains a value between 0 and 25. These values correspond to the letters 'a' to 'z' (0 = 'a', 1 = 'b', ..., 25 = 'z').

Return the lexicographically smallest string that can be formed by starting from a leaf node (a node with no children) and ending at the root of the tree. The string formed should be the lexicographically smallest among all possible strings.

Remember, any shorter prefix of a string is lexicographically smaller. For example, in lexicographical order, "ab" is smaller than "aba".

Examples

Example 1:

  • Input: root = [0, 1, 2, null, 3, 3, 4]
Image
  • Expected Output: "dba"
  • Explanation: The strings formed from the leaf nodes to the root are "dba", "dca", and "eca". The smallest string is "dba".

Example 2:

  • Input: root = [4, 0, 1, 1, 3, 2, 3]
Image
  • Expected Output: "bae"
  • Explanation: The strings formed are "bae", "dae", "cbe", and "dbe". The smallest string is "bae".

Example 3:

  • Input: root = [1, 3, 2, 3, 4, 4, 3]
Image
  • Expected Output: "dcb"
  • Explanation: The strings formed are "ddb", "edb", "ecb", and "dcb". The smallest string is "dcb".

Constraints:

  • The number of nodes in the tree is in the range [1, 8500].
  • 0 <= Node.val <= 25

Solution

To solve this problem, we employ a Depth First Search (DFS) approach to traverse the binary tree from the root to all leaf nodes. As we visit each node, we construct strings by converting the node's value to its corresponding character and appending it to a suffix string. When a leaf node is reached, the constructed string, which represents the path from that leaf to the root, is returned.

The algorithm then compares these strings from different paths, ensuring that the smallest lexicographically string is selected. By using DFS, we efficiently explore all possible paths, and by maintaining the smallest string found so far, we ensure that the final result is the smallest possible string starting from a leaf and moving towards the root.

Step-by-Step Algorithm

  1. Start at the Root:

    • Start the DFS from the root node.
  2. Check for Null Node:

    • Inside the dfs method, the first action is to check if the current node (node) is null.
    • If the node is null, return a string with the value "~". This serves as a sentinel value since it is lexicographically larger than any valid string formed by the characters 'a' to 'z'.
  3. Update the Suffix String:

    • Convert the value of the current node to its corresponding character by adding the node’s value to the ASCII value of 'a'.
    • Prepend this character to the suffix string as we need to create leaf to root string.
  4. Check for Leaf Node:

    • If the current node is a leaf, return the current suffix string as it represents a valid path from a leaf to the root.
  5. Recursive DFS on Child Nodes:

    • Recursively call the dfs method on both the left and right children of the current node.
    • Pass the updated suffix string in these recursive calls.
  6. Compare and Select the Smaller String:

    • Compare the strings returned by the left and right recursive calls using the minimum method.
    • The minimum method returns the lexicographically smaller string.
  7. Return the Smallest String:

    • Return the smallest string obtained from the comparisons. This string is propagated up the recursive call stack, eventually reaching the original call in the smallestFromLeaf method.

Algorithm Walkthrough

Given the binary tree structure for the input:

    0
   / \
  1   2
   \  / \
    3 3  4
  1. Start at Root:

    • The smallestFromLeaf method is called with the root node (0) and an empty string "".
  2. DFS on Root Node:

    • The dfs method starts with node 0. The current suffix is "a" because 0 + 'a' = 'a'.
    • The node 0 is not a leaf, so proceed to its children.
  3. DFS on Left Subtree (Node 1):

    • The dfs method is called recursively with node 1 and the current suffix "a".
    • The current suffix becomes "ba" because 1 + 'a' = 'b'.
    • Node 1 is not a leaf, so move to its children.
  4. DFS on Node 3 (Right Child of Node 1):

    • The dfs method is called recursively with node 3 and the current suffix "ba".
    • The current suffix becomes "dba" because 3 + 'a' = 'd'.
    • Node 3 is a leaf, so return "dba".
  5. DFS on Right Subtree (Node 2):

    • After completing the left subtree, the algorithm moves to the right subtree by calling dfs on node 2 with the initial suffix "a".
    • The current suffix becomes "ca" because 2 + 'a' = 'c'.
    • Node 2 is not a leaf, so move to its children.
  6. DFS on Node 3 (Left Child of Node 2):

    • The dfs method is called recursively with node 3 and the current suffix "ca".
    • The current suffix becomes "dca" because 3 + 'a' = 'd'.
    • Node 3 is a leaf, so return "dca".
  7. DFS on Node 4 (Right Child of Node 2):

    • The dfs method is called recursively with node 4 and the current suffix "ca".
    • The current suffix becomes "eca" because 4 + 'a' = 'e'.
    • Node 4 is a leaf, so return "eca".
  8. Compare Strings from Right Subtree:

    • The algorithm now has two strings from the right subtree: "dca" and "eca".
    • Compare these strings using the minimum method. "dca" is smaller, so "dca" is returned up the call stack.
  9. Compare Left and Right Subtree Results:

    • The algorithm compares "dba" (from the left subtree) and "dca" (from the right subtree) at the root node.
    • "dba" is smaller, so "dba" is returned as the final result.
  10. Output the Result:

    • The smallest string "dba" is printed as the output.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

  • The time complexity of the algorithm is , where N is the number of nodes in the binary tree.
  • This is because the algorithm performs a Depth First Search (DFS), which visits each node exactly once.

Space Complexity

  • The space complexity is , where H is the height of the tree.
  • This space is required for the recursive stack used during DFS. In the worst case, if the tree is skewed, the height H could be equal to N, leading to a space complexity of .
  • In the best case, the tree is balanced, and the space complexity would be .
Smallest String Starting From Leaf (medium)
Pseudo-Palindromic Paths in a Binary Tree (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity